package com.dq.controller.api.small;

import com.dq.exception.customException.ApiException;
import com.dq.vo.Vo;
import com.dq.domain.address.Address;
import com.dq.vo.baseVo.VO;
import com.dq.domain.sys.user.user.base.SysUser;
import com.dq.service.AllService;
import com.dq.utils.BeanNullUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * @author heshuaijun
 * @date 2019/9/1613:44
 */
@Api(description = "收货地址")
@RestController
@RequestMapping("/api/address")
public class AddressController extends AllService {
    @ApiOperation("所有收货地址列表")
    @PostMapping("/list")
    public VO list() {
        SysUser sysUser = shiroService.getUser();
        List<Address> addresses = addressRepository.findByUserAndDeletedFalse(sysUser);
        return new Vo(VO.toVOCollection(addresses, false));
    }

    @ApiOperation("新增收货地址")
    @PostMapping("/add")
    public VO add(@RequestBody Address addAddress) {
        return new Vo(addressService.addOrModifyAddress(addAddress).toVO(false));
    }

    @ApiOperation("编辑收货地址")
    @PostMapping("/edit/{addressId}")
    public VO add(@RequestBody Address updateAddress, @PathVariable @ApiParam("地址id") Long addressId) throws ApiException {
        Address address = dao.get(Address.class, addressId);
        if (address == null) {
            throw new ApiException("未找到地址");
        }
        BeanUtils.copyProperties(updateAddress, address, BeanNullUtil.getNullPropertyNames(updateAddress));
        return new Vo(addressService.addOrModifyAddress(address).toVO(false));
    }

    @ApiOperation("删除收货地址")
    @PostMapping("/delete/{addressId}")
    public VO add(@PathVariable @ApiParam("地址id") Long addressId) throws ApiException {
        Address address = dao.get(Address.class, addressId);
        if (address == null) {
            throw new ApiException("未找到地址");
        }
        address.setDeleted(true);
        addressRepository.save(address);
        return new Vo(HttpStatus.OK);
    }
}
